{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '0'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.GRUCell(size_layer,reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        def forward(x, y, reuse = False):\n",
    "            batch_size = tf.shape(x)[0]\n",
    "            X_seq_len = tf.count_nonzero(x, 1, dtype = tf.int32)\n",
    "            Y_seq_len = tf.count_nonzero(y, 1, dtype = tf.int32)\n",
    "            with tf.variable_scope('model',reuse=reuse):\n",
    "                encoder_embedded = tf.nn.embedding_lookup(embeddings, x)\n",
    "                decoder_embedded = tf.nn.embedding_lookup(embeddings, y)\n",
    "                rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n",
    "                last_output, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n",
    "                                                  sequence_length=X_seq_len,\n",
    "                                                  dtype = tf.float32)\n",
    "                \n",
    "            with tf.variable_scope(\"decoder\",reuse=reuse):\n",
    "                \n",
    "                attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(num_units = size_layer, \n",
    "                                                                    memory = last_output)\n",
    "                rnn_cells = tf.contrib.seq2seq.AttentionWrapper(\n",
    "                    cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n",
    "                    attention_mechanism = attention_mechanism,\n",
    "                    attention_layer_size = size_layer)\n",
    "                \n",
    "                initial_state = rnn_cells.zero_state(batch_size, tf.float32).clone(cell_state=last_state)\n",
    "                outputs, _ = tf.nn.dynamic_rnn(rnn_cells, decoder_embedded, \n",
    "                                               sequence_length=Y_seq_len,\n",
    "                                               initial_state = initial_state,\n",
    "                                               dtype = tf.float32)\n",
    "                \n",
    "                return tf.layers.dense(outputs,vocab_size)\n",
    "            \n",
    "        main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        self.training_logits = forward(self.X, decoder_input, reuse = False)\n",
    "        \n",
    "        self.training_logits = self.training_logits[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n",
    "            \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, 1)\n",
    "            logits = forward(x, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            1,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            vocab_size,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.fast_result = final_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-8-28bd8fd99cbb>:11: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-8-28bd8fd99cbb>:29: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-8-28bd8fd99cbb>:32: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:559: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:565: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:575: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From <ipython-input-8-28bd8fd99cbb>:49: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensor2tensor/utils/beam_search.py:745: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[[    1, 13872, 13872, 31767, 11095, 11095, 11095, 20258, 20258,\n",
       "          20258, 20258,  6960, 11142, 20354, 20354, 20354, 20354, 31683,\n",
       "          31683, 26948,  5179,  4466,  4466,  4466,  4466,  5385,  5385,\n",
       "           5385, 18081, 18081, 18081,  7270, 14117, 27127, 29460, 19935,\n",
       "           6996]],\n",
       " \n",
       "        [[    1, 21436,  9561,  9561,  7197,  9561,  7197,  5339, 26032,\n",
       "           5339,  4247, 21722,  4247, 31038, 26507, 26507, 26507, 26507,\n",
       "          26507, 15165, 15165, 15165, 22856, 22856, 24925, 24925, 17107,\n",
       "          17107, 13494, 21013, 21013, 21013, 17107,  5741,  5741,  5741,\n",
       "          29063]],\n",
       " \n",
       "        [[    1, 18442, 23238, 23238, 25687, 25687,  1263,  1263, 13867,\n",
       "          13867, 21591, 21591, 21591, 13440, 13440, 14704, 14704, 16520,\n",
       "          16520,  1165,  1165, 20886, 20886, 20886, 26485, 13691, 13691,\n",
       "          13691, 13691, 17436, 17436, 11480, 11480, 11480, 24671, 19593,\n",
       "           3945]],\n",
       " \n",
       "        [[    1,  6987,  6987, 15750, 13615, 13615, 13615, 13615, 13615,\n",
       "          13615, 21760, 20616, 14788, 31935, 31935, 30042, 30042,  9703,\n",
       "          10424, 10424, 10424, 10424, 10424, 10424, 29130, 29130, 17580,\n",
       "          17580, 17580, 22712, 22712,  8363,  8363,  8363,  8363,  8363,\n",
       "          28161]],\n",
       " \n",
       "        [[    1,  6904, 10292,  6904,  4559, 29435, 20541, 16804, 16804,\n",
       "          15974, 15974, 24759, 24759, 25652, 25652, 19656, 26384, 26384,\n",
       "          26384, 26384, 10083, 10083, 10083, 16539, 16539, 31625, 31625,\n",
       "          24519, 24519, 17010,  3843,  3843,  3843,  3843, 31827, 31827,\n",
       "          31827]],\n",
       " \n",
       "        [[    1, 24049,  3678,  3678,  3678, 29534, 29534, 29534, 29534,\n",
       "          25344, 25344, 15610, 14812,  4991,  4991,  4991,  4991,  2925,\n",
       "           2925,  3374,  3374,  3374, 15182,  9953,  9953,  9953,  9953,\n",
       "           5040, 28844, 28844, 28844, 28844, 28844, 17223, 17223, 17223,\n",
       "          17223]],\n",
       " \n",
       "        [[    1, 18918, 19900, 19900, 18515, 18515, 18515, 18515, 26826,\n",
       "          26826, 20712, 20712, 20712,  2096,  2096, 20712, 22791, 22791,\n",
       "          22791, 22791, 22791, 22791, 22791, 22791, 22571, 31728, 13564,\n",
       "          13564, 13564, 13564, 13564, 13564, 13564, 10383, 10383, 10383,\n",
       "           2889]],\n",
       " \n",
       "        [[    1, 19322, 26095, 26095, 26095, 13011, 20536,  6341,  6341,\n",
       "           6341,  6341,   713,   713,   713, 18986, 18986, 12697, 12697,\n",
       "          24567, 24567, 24567, 24567, 15730, 15730, 15730, 15730, 13663,\n",
       "          13663, 13663, 13663,  1845, 22560, 22560, 31424, 30920, 22135,\n",
       "          29185]],\n",
       " \n",
       "        [[    1,  4315,  4315,  4315, 30456, 30456, 30456, 30784, 30784,\n",
       "          30784, 23330,  9414,  9414, 16503, 16503, 22887, 22887, 15914,\n",
       "          27083, 27083, 27083, 27083, 27083, 27083, 27083,   172, 21519,\n",
       "          21519, 21519, 21519, 23056, 23056, 17458, 17458, 17458, 29126,\n",
       "          17458]],\n",
       " \n",
       "        [[    1,   272, 18498, 18498, 18498, 13936, 13936, 13936,  3903,\n",
       "           3903,  3903,  4249,  4249, 25347,  3911,  3911, 12265, 29455,\n",
       "          29455,  9967,  9967,  9967,  9967,  9967,  9967,  9967, 22833,\n",
       "          22833, 22833, 22833, 23365, 23365, 21688,  2969,  2969, 18484,\n",
       "          18484]]], dtype=int32), 10.373586, 0.0]"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:45<00:00,  2.67it/s, accuracy=0.142, cost=6.15]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.18it/s, accuracy=0.134, cost=6]   \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 6.788980, training avg acc 0.123003\n",
      "epoch 1, testing avg loss 6.129451, testing avg acc 0.149149\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:46<00:00,  2.67it/s, accuracy=0.162, cost=5.26]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.39it/s, accuracy=0.134, cost=5.9] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 5.775488, training avg acc 0.158012\n",
      "epoch 2, testing avg loss 5.788449, testing avg acc 0.158840\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:41<00:00,  2.69it/s, accuracy=0.183, cost=4.76]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.52it/s, accuracy=0.113, cost=5.92]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 5.304755, training avg acc 0.172933\n",
      "epoch 3, testing avg loss 5.755338, testing avg acc 0.156013\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:31<00:00,  2.73it/s, accuracy=0.186, cost=4.64]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.49it/s, accuracy=0.129, cost=5.66]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 4.991313, training avg acc 0.184947\n",
      "epoch 4, testing avg loss 5.654192, testing avg acc 0.158762\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:31<00:00,  2.74it/s, accuracy=0.2, cost=4.39]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.48it/s, accuracy=0.129, cost=5.71]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 4.751270, training avg acc 0.195311\n",
      "epoch 5, testing avg loss 5.669993, testing avg acc 0.159359\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:30<00:00,  2.74it/s, accuracy=0.237, cost=4.07]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.49it/s, accuracy=0.134, cost=5.8] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 4.571698, training avg acc 0.203934\n",
      "epoch 6, testing avg loss 5.719434, testing avg acc 0.157175\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:34<00:00,  2.72it/s, accuracy=0.24, cost=3.91] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.33it/s, accuracy=0.161, cost=5.83]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 4.437928, training avg acc 0.211397\n",
      "epoch 7, testing avg loss 5.738156, testing avg acc 0.161456\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:32<00:00,  2.73it/s, accuracy=0.252, cost=3.82]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.51it/s, accuracy=0.161, cost=5.84]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 4.316101, training avg acc 0.219981\n",
      "epoch 8, testing avg loss 5.850009, testing avg acc 0.160006\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:32<00:00,  2.73it/s, accuracy=0.244, cost=3.97]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.50it/s, accuracy=0.145, cost=5.97]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 4.222740, training avg acc 0.226911\n",
      "epoch 9, testing avg loss 5.872429, testing avg acc 0.158649\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:32<00:00,  2.73it/s, accuracy=0.265, cost=3.68]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.51it/s, accuracy=0.145, cost=6.11]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 4.163557, training avg acc 0.231010\n",
      "epoch 10, testing avg loss 6.055239, testing avg acc 0.152463\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:32<00:00,  2.73it/s, accuracy=0.254, cost=3.77]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.44it/s, accuracy=0.151, cost=5.88]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 4.105630, training avg acc 0.235618\n",
      "epoch 11, testing avg loss 5.968886, testing avg acc 0.157022\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:31<00:00,  2.73it/s, accuracy=0.264, cost=3.61]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.56it/s, accuracy=0.161, cost=5.65]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 4.065507, training avg acc 0.238649\n",
      "epoch 12, testing avg loss 6.020968, testing avg acc 0.154814\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:32<00:00,  2.73it/s, accuracy=0.28, cost=3.59] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.41it/s, accuracy=0.145, cost=6.19]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 4.007087, training avg acc 0.244087\n",
      "epoch 13, testing avg loss 6.049852, testing avg acc 0.154641\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:31<00:00,  2.73it/s, accuracy=0.275, cost=3.56]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.47it/s, accuracy=0.113, cost=6.48]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 3.993579, training avg acc 0.244607\n",
      "epoch 14, testing avg loss 6.105257, testing avg acc 0.155426\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:32<00:00,  2.73it/s, accuracy=0.263, cost=3.57]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.53it/s, accuracy=0.129, cost=6.18]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 3.995389, training avg acc 0.243748\n",
      "epoch 15, testing avg loss 6.062198, testing avg acc 0.155437\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:31<00:00,  2.74it/s, accuracy=0.282, cost=3.47]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.39it/s, accuracy=0.129, cost=6.2] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 3.922376, training avg acc 0.251463\n",
      "epoch 16, testing avg loss 6.159074, testing avg acc 0.155683\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:33<00:00,  2.73it/s, accuracy=0.273, cost=3.52]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.34it/s, accuracy=0.134, cost=6.41]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 3.910037, training avg acc 0.252681\n",
      "epoch 17, testing avg loss 6.202984, testing avg acc 0.153425\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:32<00:00,  2.73it/s, accuracy=0.292, cost=3.46]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.48it/s, accuracy=0.161, cost=6.15]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 3.945296, training avg acc 0.248735\n",
      "epoch 18, testing avg loss 6.194018, testing avg acc 0.153860\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:32<00:00,  2.73it/s, accuracy=0.259, cost=3.62]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.54it/s, accuracy=0.145, cost=6.22]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 3.922567, training avg acc 0.250986\n",
      "epoch 19, testing avg loss 6.230792, testing avg acc 0.154232\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:23<00:00,  2.78it/s, accuracy=0.265, cost=3.64]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.40it/s, accuracy=0.134, cost=6.04]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 4.049239, training avg acc 0.237949\n",
      "epoch 20, testing avg loss 6.154497, testing avg acc 0.153501\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [02:43<00:00,  4.09s/it]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)[:,0,:]\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.025584696"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
